<template>
  <div class="register-container">
    <div class="register-card">
      <h2 class="title">欢迎注册蜗牛商学院</h2>
      <el-form ref="registerForm" :model="form" :rules="rules" label-width="80px" class="form">
        <!-- 昵称 -->
        <el-form-item label="昵称" prop="teacherName">
          <el-input v-model="form.teacherName" placeholder="输入昵称" clearable :disabled="isDisabled" />
        </el-form-item>

        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="输入密码" clearable :disabled="isDisabled" />
        </el-form-item>

        <!-- 手机号 -->
        <el-form-item label="手机号" prop="telephone">
          <el-input v-model="form.telephone" placeholder="输入手机号码" clearable prefix-icon="el-icon-phone"
            :disabled="isDisabled">
            <template #prefix>
              <span class="country-code">+86</span>
            </template>
          </el-input>
        </el-form-item>

        <!-- 验证码 -->
        <el-form-item label="验证码" prop="code">
          <div class="code-row">
            <el-input v-model="form.code" placeholder="短信验证码" clearable style="flex: 1; margin-right: 8px;" />
            <el-button type="primary" size="mini" @click="sendCode" :disabled="codeButtonDisabled">
              {{ codeButtonText }}
            </el-button>
          </div>
        </el-form-item>

        <!-- 协议行（核心优化：完全同行显示） -->
        <el-form-item label="" class="agreement-row">
          <div class="flex items-center space-x-1">
            <el-checkbox v-model="form.agree" style="vertical-align: middle; margin-right: 0px;" />
            <span style="vertical-align: middle; font-size: 13px;">
              已阅读并同意
              <a href="javascript:void(0)" class="protocol-link" @click="openAgreement">服务协议</a>
              和
              <a href="javascript:void(0)" class="protocol-link" @click="openPrivacy">隐私说明</a>
            </span>
          </div>
        </el-form-item>

        <!-- 注册按钮（居中） -->
        <el-form-item style="text-align: center;">
          <el-button type="primary" class="register-btn" @click="handleRegister">
            立即注册
          </el-button>
        </el-form-item>
        <el-form-item style="text-align: center;">
          <el-button type="primary" class="register-btn" @click="backlogin">
            返回登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
  
<script setup>
  import { ref, reactive } from 'vue'
  import { ElMessage } from 'element-plus'
  import axios from 'axios'
import router from '@/router';

  
  // 表单数据
  const form = reactive({
    teacherName: '',
    password: '',
    telephone: '',
    code: '',
    agree: false
  })

  const isDisabled = ref(false);  // 默认不禁用
  
  // 表单校验规则
  const rules = {
    teacherName: [
      { required: true, message: '请输入昵称', trigger: 'blur' },
      { min: 2, max: 16, message: '长度在 2 到 16 个字符', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
    ],
    telephone: [
      { required: true, message: '请填写手机号', trigger: 'blur' },
      { pattern: /^1\d{10}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    code: [
      { required: true, message: '请输入短信验证码', trigger: 'blur' },
      { min: 4, max: 6, message: '验证码格式错误', trigger: 'blur' }
    ]
  }
  
  // 验证码按钮状态
  const codeButtonText = ref('发送验证码')
  const codeButtonDisabled = ref(false)
  
  // 发送验证码
  const sendCode = () => {
  // 验证用户名
  if (!form.teacherName) {
    ElMessage.error('请填写用户名')
    return
  }
  
  // 验证密码
  if (!form.password) {
    ElMessage.error('请填写密码')
    return
  }
  
  // 验证手机号
  if (!form.telephone) {
    ElMessage.error('请填写手机号码')
    return
  }
  
  // 验证手机号格式
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phoneRegex.test(form.telephone)) {
    ElMessage.error('手机号码格式不正确')
    return
  }
  
  // 所有字段验证通过，发送验证码请求
  axios.post("http://192.140.166.207:8088/api/TeachersController/register", form).then(res => {
    if (res.data.code === 200) {
      ElMessage({
        showClose: true,
        message: "验证码发送成功",
        type: 'success',
      })
      // 启动倒计时
      startCountdown()
      isDisabled.value = !isDisabled.value;
    } else{
      throw new Error('登录信息更新失败');
    }
  }).catch(error => {
    console.error('操作失败:', error);
    ElMessage({
        showClose: true,
        message: "用户名或手机号已被使用",
        type: 'warning',
      })
  })
}

// 抽取倒计时逻辑为单独函数
const startCountdown = () => {
  codeButtonDisabled.value = true
  codeButtonText.value = '60s后重发'
  
  let timer = setInterval(() => {
    let count = parseInt(codeButtonText.value)
    if (count <= 1) {
      clearInterval(timer)
      codeButtonText.value = '发送验证码'
      codeButtonDisabled.value = false
    } else {
      codeButtonText.value = (count - 1) + 's后重发'
    }
  }, 1000)
}
  
  // 打开协议/隐私说明（可扩展弹窗展示内容）
  const openAgreement = () => {
    ElMessage.info('服务协议：使用本平台需遵守基本规则，保障双方权益。')
  }
  const openPrivacy = () => {
    ElMessage.info('隐私说明：我们会保护你的注册信息，不会随意泄露。')
  }
  
  // 注册提交
const handleRegister = () => {
    if (!form.agree) {
      ElMessage.error('请阅读并同意协议和隐私说明')
      return
    }
    // 这里可写真实接口请求逻辑
    axios.post("http://192.140.166.207:8088/api/TeachersController/checkCode", form).then(res => {
      if (res.data.code === 200) {
        ElMessage({
          showClose: true,
          message: "注册成功",
          type: 'success',
        })
        form.agree=false;
        form.code="";
        form.teacherName="";
        form.password="";
      }
    }).catch(error => {
      ElMessage({
        showClose: true,
        message: "注册失败",
        type: 'warning',
      })
    })
}

const backlogin =()=>{
  router.push("/")
}
  </script>
  
  <style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: #f4f4f4;
  position: relative; /* 新增，为绝对定位的返回箭头做准备 */
}

/* 返回箭头样式 */
.back-arrow-container {
  position: absolute;
  top: 20px;
  left: 20px;
  font-size: 24px;
  color: #666;
  text-decoration: none;
}
.back-arrow {
  cursor: pointer;
  transition: color 0.3s ease;
}
.back-arrow:hover {
  color: #409eff;
}

.register-card {
  width: 400px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 24px;
  position: relative; /* 防止内容被绝对定位的箭头覆盖（可选，视情况调整） */
}

.title {
  text-align: center;
  font-size: 20px;
  margin-bottom: 20px;
  color: #333;
}

.form {
  width: 100%;
}

.country-code {
  color: #999;
  margin-right: 8px;
}

.code-row {
  display: flex;
  align-items: center;
}

.protocol-link {
  color: #409eff;
  text-decoration: none;
  margin: 0 4px;
}

.register-btn {
  width: 160px;
}

.register-container {
  position: relative; /* 为绝对定位的箭头做准备 */
  /* 原有样式... */
}
.back-arrow {
  position: absolute;
  top: 20px; /* 可根据实际调整 */
  left: 20px; /* 可根据实际调整 */
  font-size: 24px;
  color: #666;
  text-decoration: none;
  cursor: pointer;
  transition: color 0.3s ease;
}
.back-arrow:hover {
  color: #409eff; /*  hover 变色，可自定义 */
}
</style>